package logic

import (
	"context"
	"errors"
	"manuscript-service/model/mysql"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFileAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileAddLogic {
	return &FileAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加方法
func (l *FileAddLogic) FileAdd(in *servicerpc.FileAddRequest) (*servicerpc.FileAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Begin()

	var findFiles mysql.Files

	if err := findFiles.FindFilesByName(begin, in.Name); err == nil {
		begin.Rollback()
		return nil, errors.New("商品已存在")
	}

	class := &mysql.Class{
		Name: in.Name,
	}

	if err := class.FindClassByName(begin, in.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}

	files := &mysql.Files{
		Name:    in.Name,
		Context: in.Context,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}

	if err := files.FileAdd(begin); err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()

	return &servicerpc.FileAddResponse{
		FilesId: int64(files.ID),
	}, nil
}
